/**
 * 
 */
package com.yi.model.internal.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.util.StringUtils;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.yi.model.db.mongo.MongoDBHelper;
import com.yi.model.internal.IBussModelApi;
import com.yi.model.objects.DBDefinitions;
import com.yi.model.objects.Field;
import com.yi.model.objects.BussModel;
import com.yi.model.objects.IModel;
import com.yi.model.objects.ModelUIConfig;
import com.yi.role.objects.Role;

/**
 * @author long
 *
 */
public class BussModelApi extends ModelApi  implements IBussModelApi{

	private MongoDBHelper dbHelper;
	public MongoDBHelper getDbHelper() {
		return dbHelper;
	}
	
	@Override
	public String create(final String collName,final BussModel bussModel) {
		// TODO Auto-generated method stub
		return getDbHelper().addEntity(collName, convertBuzzModelToEntity(bussModel));
	}

	@Override
	public BussModel view(final String collName,String id) {
		// TODO Auto-generated method stub
		return convertEntityToBuzzModel(getDbHelper().viewEntityById(collName, id));
	}

	@Override
	public void update(final String collName,BussModel bussModel) {
		// TODO Auto-generated method stub
		getDbHelper().updateEntity(collName, convertBuzzModelToEntity(bussModel));
	}

	@Override
	public void delete(final String collName,String id) {
		// TODO Auto-generated method stub
		getDbHelper().removeEntityById(collName, id);
	}

	@Override
	public List<BussModel> list(final String collName, int pageNumber) {
		// TODO Auto-generated method stub
		List<DBObject> matches = getDbHelper().findEntities(collName, pageNumber);
		List<BussModel> models = new ArrayList<BussModel>();
		for(DBObject entity : matches){
			models.add(convertEntityToBuzzModel(entity));
		}
		return models;
	}

	private DBObject convertBuzzModelToEntity(BussModel model){
		DBObject entity = convertModelToEntity(model);
		entity.put(DBDefinitions.col_modelType_id, model.modelTypeId);
		return entity;
	}
	
	private BussModel convertEntityToBuzzModel(DBObject entity){
		BussModel model = new BussModel(convertEntityToModel(entity));
		if(entity.get(DBDefinitions.col_modelType_id) != null) model.modelTypeId = entity.get(DBDefinitions.col_modelType_id).toString();
		return model;
	}

	public void setDbHelper(MongoDBHelper dbHelper) {
		this.dbHelper = dbHelper;
	}

}
